<template>
  <div class="app-container">
    <div style="padding: 5px 0px">
      <div class="banance-toolbar">
        <div>
          <span
            ><el-button type="primary" size="small" @click="handleCheck">
              试算平衡
            </el-button></span
          >
          <span style="margin-left: 10px" v-if="!settlement.closed"
            ><el-button
              type="warning"
              size="small"
              @click="() => handleInitialization(true)"
              >完成初始化</el-button
            ></span
          >
          <span style="margin-left: 10px" v-if="settlement.closed == true"
            ><el-button
              type="danger"
              size="small"
              @click="() => handleInitialization(false)"
              >重新初始化</el-button
            ></span
          >
          <span style="margin-left: 10px"
            ><el-button size="small" @click="() => handleDelete()"
              >清空</el-button
            ></span
          >
          <span style="margin-left: 10px">
            <el-dropdown @command="handleCommand">
              <el-button>
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="export" icon="el-icon-download"
                  >导出</el-dropdown-item
                >
                <el-dropdown-item command="import" icon="el-icon-upload2"
                  >导入</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </span>
          <span style="margin-left: 10px">
            <el-button
              icon="el-icon-search"
              circle
              size="small"
              @click="handleSearch"
            ></el-button>
          </span>

          <span style="margin-left: 10px; float: right"
            ><i class="el-icon-refresh" @click="handleRefresh">{{
              $t("common.refresh")
            }}</i></span
          >
        </div>

        <div
          v-show="showSearch"
          style="padding-top: 10px; padding-bottom: 10px"
        ></div>
      </div>
      <div class="banance-content">
        <vxe-table
          border
          resizable
          :tree-config="{
            children: 'children',
            accordion: false,
            expandAll: true,
          }"
          :data="list"
          @cell-dblclick="handleRowClick"
          default-expand-all
        >
          <vxe-table-column
            field="accountCode"
            title="编码"
            tree-node
          ></vxe-table-column>
          <vxe-table-column field="accountName" title="名称"></vxe-table-column>
          <vxe-table-column field="openingAmount" title="期初余额">
            <template v-slot="{ row }">
              <amount-panel
                field="openingAmount"
                :items="row.items"
              ></amount-panel>
            </template>
          </vxe-table-column>
          <vxe-table-column field="currentYearDebitAmount" title="本年累计借方">
            <template v-slot="{ row }">
              <amount-panel
                field="currentYearDebitAmount"
                :items="row.items"
              ></amount-panel>
            </template>
          </vxe-table-column>
          <vxe-table-column
            field="currentYearCreditAmount"
            title="本年累计贷方"
          >
            <template v-slot="{ row }">
              <amount-panel
                field="currentYearCreditAmount"
                :items="row.items"
              ></amount-panel>
            </template>
          </vxe-table-column>
        </vxe-table>
      </div>
    </div>
    <el-dialog title="试算结果" :visible.sync="showTrailDialog" width="50%">
      <div>
        <div>
          <el-link type="success" v-if="trailResult.passed">通过</el-link>
          <el-link type="danger" v-if="!trailResult.passed">不通过</el-link>
        </div>
        <div>
          <el-row>
            <el-col :span="6">类型</el-col>
            <el-col :span="9">借方</el-col>
            <el-col :span="9">贷方</el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row>
            <el-col :span="6">期初</el-col>
            <el-col :span="9">{{
              trailResult.debitOpeningAmount | money
            }}</el-col>
            <el-col :span="9">{{
              trailResult.creditOpeningAmount | money
            }}</el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row>
            <el-col :span="6">本年累计</el-col>
            <el-col :span="9">{{
              trailResult.currentYearDebitAmount | money
            }}</el-col>
            <el-col :span="9">{{
              trailResult.currentYearCreditAmount | money
            }}</el-col>
          </el-row>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showTrailDialog = false" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <el-drawer
      direction="rtl"
      :visible.sync="importDrawer"
      :with-header="false"
      style="overflow: auto"
    >
      <div v-if="importDrawer">
        <importPanel
          :moduleCode="$enums.moduleType.initialBalance.value"
        ></importPanel>
      </div>
    </el-drawer>
    <export-panel
      v-show="false"
      ref="export"
      :moduleCode="$enums.moduleType.initialBalance.value"
    ></export-panel>
  </div>
</template>
<script>
import {
  getInitalizations,
  trialBalance,
  clearBalances,
} from "@/api/accountBalance";
import { getSettlements, closePeriod, openPeriod } from "@/api/settlement";
import amountPanel from "./amountPanel";
import importPanel from "@/components/Import/index.vue";
import exportPanel from "@/components/Export/index.vue";
export default {
  components: {
    amountPanel,
    importPanel,
    exportPanel,
  },
  data() {
    return {
      list: [],
      showSearch: false,
      showTrailDialog: false,
      trailResult: {},
      settlement: {},
      importDrawer: false,
    };
  },
  methods: {
    getData() {
      getInitalizations().then((res) => {
        res = res || [];
        this.list = res.toTree();
      });
    },
    getSettlement() {
      getSettlements({ period: this.openingPeriod }).then((res) => {
        if (res && res.length > 0) this.settlement = res[0];
      });
    },
    handleRowClick({ row }) {
      this.handleEdit(row.accountId);
    },
    handleCheck() {
      trialBalance().then((res) => {
        if (!res) return;
        this.showTrailDialog = true;
        this.trailResult = res;
      });
    },
    handleInitialization(close) {
      let period = this.openingPeriod;
      if (close) {
        closePeriod(period).then((res) => {
          if (!res) return;
          this.$notify({
            title: "成功",
            message: "已完成初始化",
            type: "success",
            position: "bottom-right",
          });
          this.getSettlement();
        });
      } else {
        openPeriod(period).then((res) => {
          if (!res) return;
          this.$notify({
            title: "成功",
            message: "已重新初始化",
            type: "success",
            position: "bottom-right",
          });
          this.getSettlement();
        });
      }
    },
    handleEdit(accountId) {
      if (!this.standardCurrency) {
        this.$notify.error({
          title: "错误",
          message: "请先设置组织财务信息",
          position: "bottom-right",
        });

        return;
      }
      this.$router.push({
        name: "OpeningBalanceEdit",
        query: {
          accountId: accountId,
        },
      });
    },
    handleDelete() {
      this.$confirm("删除的数据无法恢复，是否继续？", "清空余额", {
        confirmButtonText: this.$t("common.ok"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          clearBalances().then((res) => {
            this.getData();
          });
        })
        .catch(() => {});
    },
    handleRefresh() {
      this.getData();
    },
    handleSearch() {},
    handleCommand(command) {
      if (command == "export") this.handleExport();
      else if (command == "import") this.handleImport();
    },
    handleExport() {
      this.$refs.export.exportData();
    },
    handleImport() {
      this.importDrawer = true;
    },
  },
  mounted() {
    this.getSettlement();
    this.getData();
  },
  computed: {
    org() {
      return this.$store.state.organization.data;
    },
    standardCurrency() {
      return this.org.currencyId;
    },
    openingPeriod() {
      let activationDate = this.org.activationDate;

      if (!activationDate) return 0;
      activationDate = new Date(activationDate);
      return activationDate.getFullYear() * 100 + activationDate.getMonth();
    },
  },
};
</script>
<style scoped>
.banance-content {
  padding-top: 20px;
}
</style>
